package cc.mrbird.febs.statistics.controller;

import cc.mrbird.febs.accounting.Constant.CompanyConstant;
import cc.mrbird.febs.accounting.dto.detailCost.DetailCostParam;
import cc.mrbird.febs.accounting.dto.detailCost.DetailTotalDTO;
import cc.mrbird.febs.accounting.dto.importAndExport.ExportParam;
import cc.mrbird.febs.accounting.dto.importAndExport.ImportDataDTO;
import cc.mrbird.febs.accounting.dto.importAndExport.ImportExcelData;
import cc.mrbird.febs.accounting.dto.importAndExport.ImportParam;
import cc.mrbird.febs.accounting.dto.standardSub.SingleExportDTO;
import cc.mrbird.febs.accounting.dto.standardSub.SubExportData;
import cc.mrbird.febs.accounting.entity.DetailCost;
import cc.mrbird.febs.accounting.entity.MainExportData;
import cc.mrbird.febs.accounting.entity.Project;
import cc.mrbird.febs.accounting.entity.ProjectType;
import cc.mrbird.febs.accounting.service.IDetailCostService;
import cc.mrbird.febs.accounting.service.IProjectService;
import cc.mrbird.febs.accounting.service.IProjectTypeService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.statistics.service.IDataExportService;
import cc.mrbird.febs.utils.CodeConstant;
import cc.mrbird.febs.utils.StyleMap;
import cc.mrbird.febs.utils.YearMonthMapUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping(value = "/dataExport")
public class DataExportController extends BaseController {

    @Resource
    private IDataExportService dataExportService;
    @Resource
    private IProjectService projectService;
    @Resource
    private IProjectTypeService projectTypeService;

    @GetMapping("dataExport")
    // 获取到和前端相对应的detailCost/exportSingle params中params所对应的各字段名字，year和params中的name:year是同一个
    public void download(HttpServletResponse response, @RequestParam("year") String year, @RequestParam("month") String month,
                         @RequestParam("projectId") String projectId, @RequestParam("typeId") String typeId, @RequestParam("excelType") Integer excelType) throws IOException {
        // 创建一个xlsx类型的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //List<SingleExportDTO> singleExportDTOS = this.detailCostService.querySingleExportData(projectId, year);
        // 将从params中获取到的month以数组的形式存入字符数组months中
        String[] months = month.split(",");
        // 创建一个空字符数组 yearMonths
        List<String> yearMonths = new ArrayList<>();
        // 使yearMonths里面存的是规范为yy-mm的年月（如2022-04）
        for (String e : months) {
            if (Integer.parseInt(e) < 10) {
                yearMonths.add(year + "-0" + e);
            } else {
                yearMonths.add(year + "-" + e);
            }
        }
        // Arrays.asList(projectId.split(","))是选中的project_id,指把选中的项目所对应的Id放入字符数组中，比如（选择浙江丽水的，对应的id是81，把表里的所有数据放入字符数组中)
        // this.projectService.getProjectByIds是去数据库里找选中的这个project_id对应的数据
        List<Project> projects = this.projectService.getProjectByIds(Arrays.asList(projectId.split(",")));
        List<ProjectType> types = this.projectTypeService.getProjectTypeByIds(Arrays.asList(typeId.split(",")));
//        Set<String> typeIds = new HashSet();
//        for (Project project : projects) {
//           typeIds.add(project.getTypeId());
//        }
        this.dataExportService.queryDetailForExcel(projects, types, year, yearMonths, excelType, workbook);
        String filePath = year.concat("分表汇总表").concat(".xlsx");
        response.reset();//清除buffer缓存
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(filePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));// 定义文件名
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", " 0");

        try {
            OutputStream output;
            output = response.getOutputStream();
            BufferedOutputStream bufferOutput = new BufferedOutputStream(output);
            bufferOutput.flush();
            workbook.write(bufferOutput);
            bufferOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
